package org.light.limitedverb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.log4j.Logger;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Field;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.exception.ValidateException;
import org.light.utils.DomainTokenUtil;
import org.light.utils.TableStringUtil;
import org.light.utils.WriteableUtil;

public class CountSearchByFieldsRecords extends NoControllerVerb {
	protected static Logger logger = Logger.getLogger(CountSearchByFieldsRecords.class);
	protected Set<Field> deniedFields = new TreeSet<>();
	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("CountSearch" + domain.getCapFirstPlural() + "ByFieldsRecords");
			method.setNoContainer(false);
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getLowerFirstDomainName(),new Type(this.domain.getDomainSuffix()+"."+this.domain.getType())));
			method.addSignature(new Signature(3, "ignoreMap","map[string]bool"));
			method.setReturnType(new Type("int"));
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"query := \"select count(*) countSum from " + domain.getDbPrefix() + TableStringUtil.domainNametoTableName(domain) +" where 1=1 \""));
			sList.add(new Statement(2000L,0,""));
			sList.add(new Statement(4000L,0,""));
			int index = 0;
			long serial = 5000L;
			for (Field f: this.domain.getSearchFields()) {
				if (!deniedFields.contains(f)) {
					if (f.getFieldType().equals("string")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" like '%\"+"+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"()+\"%' \""));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					} else if (f.getFieldType().equals("bool")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatBool("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"())"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					} else if (f.getFieldType().equals("int64")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatInt("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 10)"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					} else if (f.getFieldType().equals("int32")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+fmt.Sprint("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+")"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}else if (f.getFieldType().equals("int")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.Itoa("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+")"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}else if (f.getFieldType().equals("float")||f.getFieldType().equals("float64")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatFloat("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 'f', 4, 64)"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}else if (f.getFieldType().equals("float32")) {
						sList.add(new Statement(serial,1,"if _, ok := ignoreMap[\""+f.getLowerFirstFieldName()+"\"]; !ok {"));
						sList.add(new Statement(serial+1000L,2,"query"+index+" := \" and "+DomainTokenUtil.changeDomainFieldtoTableColum(f.getFieldName())+" = \"+strconv.FormatFloat("+this.domain.getLowerFirstDomainName()+".Get"+f.getCapFirstFieldName()+"(), 'f', 4, 32)"));
						sList.add(new Statement(serial+3000L,2,"query += query"+index+""));
						sList.add(new Statement(serial+4000L,1,"}"));
					}
					serial += 5000L;
					index ++;
				}					
			}
			sList.add(new Statement(serial+18000L,0,""));
			sList.add(new Statement(serial+19000L,1,"stmt, err := db.Prepare(query)"));
			sList.add(new Statement(serial+19500L,1,"defer stmt.Close()"));
			sList.add(new Statement(serial+20000L,1,"if err != nil {"));
			sList.add(new Statement(serial+21000L,2,"panic(err)"));
			sList.add(new Statement(serial+22000L,1,"}"));
			sList.add(new Statement(serial+23000L,0,""));
			sList.add(new Statement(serial+24000L,1,"row := stmt.QueryRow()"));
			sList.add(new Statement(serial+25000L,0,""));
			sList.add(new Statement(serial+26000L,1,"var count int"));
			sList.add(new Statement(serial+27000L,1,"err = row.Scan(&count)"));
			sList.add(new Statement(serial+28000L,1,"if err != nil {"));
			sList.add(new Statement(serial+29000L,2,"panic(err)"));
			sList.add(new Statement(serial+30000L,1,"}"));
			sList.add(new Statement(serial+31000L,1,"return count"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public String generateDaoImplMethodString() throws Exception {
		if (this.denied)
			return null;
		else {
			Method m = this.generateDaoImplMethod();
			String s = m.generateMethodString();
			return s;
		}
	}

	@Override
	public String generateDaoImplMethodStringWithSerial() throws Exception {
		if (this.denied)
			return null;
		else {
			Method m = this.generateDaoImplMethod();
			m.setContent(m.generateMethodContentStringWithSerial());
			m.setMethodStatementList(null);
			return m.generateMethodString();
		}
	}

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("CountSearch" + this.domain.getCapFirstPlural() + "ByFieldsRecords");
			method.setReturnType(new Type("int64"));
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getLowerFirstDomainName(), this.domain.getType(),
					this.domain.getPackageToken()));
			method.addSignature(new Signature(3, "ignoreMap","map[string]bool"));
			return method;
		}
	}

	@Override
	public String generateDaoMethodDefinitionString() throws Exception {
		if (this.denied)
			return null;
		else {
			return generateDaoMethodDefinition().generateMethodDefinition();
		}
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("CountSearch" + this.domain.getCapFirstPlural() + "ByFieldsRecords");
			method.setReturnType(new Type("int64"));
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(), this.domain.getType()));
			method.addSignature(new Signature(2, "ignoreMap","map[string]bool"));
			return method;
		}
	}

	@Override
	public String generateServiceMethodDefinitionString() throws Exception {
		if (this.denied)
			return null;
		else {
			return generateServiceMethodDefinition().generateMethodDefinition();
		}
	}

	@Override
	public Method generateServiceImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName("CountSearch" + this.domain.getCapFirstPlural() + "ByFieldsRecords");
			method.setReturnType(new Type("int"));
			method.addSignature(new Signature(1, this.domain.getLowerFirstDomainName(), new Type(this.domain.getDomainSuffix()+"."+this.domain.getType())));
			method.addSignature(new Signature(2, "ignoreMap","map[string]bool"));
			Method daomethod = this.generateDaoMethodDefinition();
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,1,"db := database.DB"));
			list.add(new Statement(2000L, 1, "return "
					+ daomethod.generateStandardDaoImplCallString(this.domain.getDaoimplSuffix())));
			method.setMethodStatementList(WriteableUtil.merge(list));

			return method;
		}
	}

	@Override
	public String generateServiceImplMethodString() throws Exception {
		if (this.denied)
			return null;
		else {
			return generateServiceImplMethod().generateMethodString();
		}
	}

	@Override
	public String generateServiceImplMethodStringWithSerial() throws Exception {
		if (this.denied)
			return null;
		else {
			Method m = this.generateServiceImplMethod();
			m.setContent(m.generateMethodContentStringWithSerial());
			m.setMethodStatementList(null);
			return m.generateMethodString();
		}
	}

	public CountSearchByFieldsRecords(Domain domain) throws ValidateException {
		super();
		this.domain = domain;
		this.dbType = "MariaDB";
		this.denied = domain.isVerbDenied("SearchByFieldsByPage");
		this.verbName = "countSearch" + this.domain.getCapFirstPlural() + "ByFieldsRecords";
	}
	
	public CountSearchByFieldsRecords(Domain domain,String dbType) throws ValidateException {
		super();
		this.domain = domain;
		this.dbType = dbType;
		this.denied = domain.isVerbDenied("SearchByFieldsByPage");
		this.verbName = "countSearch" + this.domain.getCapFirstPlural() + "ByFieldsRecords";
	}

	public CountSearchByFieldsRecords() {
		super();
		this.dbType = "MariaDB";
	}
	
	public CountSearchByFieldsRecords(String dbType) {
		super();
		this.dbType = dbType;
	}

	public Set<Field> getDeniedFields() {
		return deniedFields;
	}

	public void setDeniedFields(Set<Field> deniedFields) {
		this.deniedFields = deniedFields;
	}

}
